#ifndef DOWNLOADTOOL_H
#define DOWNLOADTOOL_H

#include <QObject>
#include <QUrl>
#include <QFile>
#include <QDir>
#include <QPointer>
#include <QApplication>

#include <QNetworkReply>
#include <QNetworkAccessManager>

#define DOWNLOAD_DEBUG

class DownloadTool : public QObject
{
    Q_OBJECT

  public:
    explicit DownloadTool(const QString& downloadUrl, const QString& savePath = QString(), QObject* parent = nullptr);
    ~DownloadTool();

    void    startDownload();
    void    cancelDownload();
    QString getFileName();
    bool    getDownloadSuccessFlag();
    QUrl    getgetDownloadUrl();

  Q_SIGNALS:
    void sigProgress(qint64 bytesRead = 0, qint64 totalBytes = 0, qreal progress = 0.0);
    void sigDownloadFinished();
    void sigDownloadFailed();

  private Q_SLOTS:
    void httpFinished();
    void httpReadyRead();
    void networkReplyProgress(qint64 bytesRead, qint64 totalBytes);

  private:
    QFile* openFileForWrite(const QString& fileName);
    void   startRequest(const QUrl& requestedUrl);

  private:
    QString                 m_downloadUrl;
    QString                 m_savePath;

    QUrl                    m_url;
    QNetworkAccessManager   m_qnam;
    QPointer<QNetworkReply> m_reply;
    QScopedPointer<QFile>   m_file;
    bool                    m_httpRequestAborted;
    bool                    m_httpSuccessed = false;
    QString                 m_fileName;
};

#endif  // DOWNLOADTOOL_H
